import React, { useState, useEffect, useCallback } from 'react';
import { Tabs } from 'antd';
import type { TabsProps } from 'antd';

interface DataTabsProps<T> {
  initialData: T[];
  initialTotalPages: number;
  categoryId?: number;
  fetchFunction: (tab: string, page: number, categoryId?: number) => Promise<{
    success: boolean;
    data: {
      [key: string]: T[] | number;
      totalPages: number;
    };
  }>;
  renderContent: (data: T[], loading: boolean, onPageChange: (page: number) => void, totalPages: number) => React.ReactNode;
  tabs: Array<{
    key: string;
    label: string;
  }>;
  defaultActiveTab?: string;
}

export default function DataTabs<T>({
  initialData,
  initialTotalPages,
  categoryId,
  fetchFunction,
  renderContent,
  tabs,
  defaultActiveTab
}: DataTabsProps<T>) {
  const [activeTab, setActiveTab] = useState<string>(defaultActiveTab || tabs[0]?.key || '');
  const [data, setData] = useState<T[]>(initialData);
  const [totalPages, setTotalPages] = useState(initialTotalPages);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);

  // 当分类ID变化时，重置页码为1
  useEffect(() => {
    setPage(1);
    if (activeTab !== (defaultActiveTab || tabs[0]?.key)) {
      setActiveTab(defaultActiveTab || tabs[0]?.key || '');
    } else {
      fetchData(activeTab, 1);
    }
  }, [categoryId, activeTab, defaultActiveTab, tabs]);

  // 当页码或Tab变化时，获取数据
  useEffect(() => {
    if (page > 1 || (page === 1 && data !== initialData)) {
      fetchData(activeTab, page);
    }
  }, [activeTab, page]);

  const fetchData = useCallback(async (tab: string, pageNum: number) => {
    setLoading(true);
    try {
      const res = await fetchFunction(tab, pageNum, categoryId);
      if (res.success) {
        const responseData = res.data;
        // 处理不同的数据结构
        const resultData = responseData.articles || responseData.cases || responseData.data || [];
        setData(Array.isArray(resultData) ? resultData : []);
        setTotalPages(responseData.totalPages || 1);
      }
    } catch (error) {
      console.error("Failed to fetch data:", error);
    } finally {
      setLoading(false);
    }
  }, [fetchFunction, categoryId]);

  const handleTabClick = (tab: string) => {
    setPage(1);
    setActiveTab(tab);
  };
  
  const handlePageChange = (newPage: number) => {
    setPage(newPage);
  };

  const tabItems: TabsProps['items'] = tabs.map(tab => ({
    key: tab.key,
    label: tab.label,
    children: renderContent(data, loading, handlePageChange, totalPages)
  }));

  return (
    <div className="bg-white rounded-xl border border-gray-200 shadow-sm">
      <Tabs
        activeKey={activeTab}
        onChange={handleTabClick}
        items={tabItems}
        className="p-6"
      />
    </div>
  );
} 